<script>
export default {
  name: "LoginCom",
  data() {
    return {
      // 验证码
      securityCode: '',
      // 登录组件与注册组件的区分变量
      loginNum: 1,
      // 验证码输入框的显隐状态
      isVerificationSent: false,
      // 表单的数据
      ruleForm: {
        // 用户的手机号或邮箱
        username: '',
        // 用户的密码
        password: '',
        // 用户输入的验证码
        subPassword: '',

      },
      // 校验规则
      rules: {
        username: [
          {required: true, message: '必须填入该项', trigger: 'blur'},
          {validator: this.validateName, trigger: 'blur'}
        ],
        subPassword: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {min: 1, max: 6, message: '长度为 6 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请设置你的密码', trigger: 'blur'},
          {min: 6, max: 12, message: '长度在6 - 12 个字符', trigger: 'blur'}
        ],
      }
    };
  },
  methods: {
    // 自定义手机号邮箱验证规则
    validateName(rule, value, callback) {
      // 手机号 正则表达式 []:一个符合条件的字符
      const phoneRegex = /^1[3-9]\d{9}$/;
      // 邮箱正则表达式
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

      if (!phoneRegex.test(value) && !emailRegex.test(value)) {
        callback(new Error('请输入有效手机号或有效的邮箱地址'));
      } else {
        if (this.loginNum === 0) {
          this.$http.post('/user/findUser', {username: value})
              .then(res => {
                console.info(res)
                if (res.data.code === 200 && res.data.msg === 1) {
                  callback();
                } else {
                  callback(new Error('该用户已存在'));
                }
              })
        } else {
          callback();
        }

      }
    },
    // 根据手机号获取验证码
    getYanZhengMa(formName) {
      // 只验证 phone 字段
      this.$refs[formName].validateField('username', (phoneError) => {
        if (!phoneError) {
          this.$message({
            message: '验证码发送成功',
            type: 'success'
          });
          this.isVerificationSent = true
          setTimeout(() => {
            // 随机生成6位数
            let number = Math.floor(Math.random() * 900000) + 100000;
            this.securityCode = number;
            console.info(number);
          }, 3000);
        } else {
          this.$message.error(`格式错误: ${phoneError}`);
        }
      });
    },
    // 提交表单
    async submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.loginNum === 1) {
            this.$http.post('/user/login', {username: this.ruleForm.username, password: this.ruleForm.password})
                .then(res => {
                  console.info(res)
                  if (res.data.code === 200 && res.data.msg === 1) {
                    const userInfo = res.data.main;
                    sessionStorage.setItem('user_info', JSON.stringify(userInfo))

                    const loading = this.$loading({
                      lock: true,
                      text: 'Loading',
                      spinner: 'el-icon-loading',
                      background: 'rgba(0, 0, 0, 0.7)'
                    });
                    setTimeout(() => {
                      loading.close();
                      this.$router.push("/userLogin")
                      this.$message({message: '登录成功', type: 'success'});
                    }, 500);


                  } else {
                    this.$message.error("用户名或密码错误");
                  }
                })
          } else {
            // 注册
            if (Number(this.ruleForm.subPassword) !== Number(this.securityCode)) {
              this.$message.error(`验证码错误`);
            } else {
              this.$http.post('/user/register', {username: this.ruleForm.username, password: this.ruleForm.password})
                  .then(res => {
                    console.info(res)
                    if (res.data.code === 200 && res.data.msg === 1) {
                      const userId = res.data.main.id;
                      // 保存登陆的用户id到会话
                      sessionStorage.setItem('user_id', JSON.stringify(userId))
                      this.$message({message: '注册成功', type: 'success'});
                    } else {
                      this.$message.error("注册失败");
                    }
                  })
            }
          }

        } else {
          this.$message.error(`请完善表单`);
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  }
}
</script>

<template>
  <div class="app">
    <div style="width: 800px;height: 400px;background-color: #fff4f4">
      <el-row>
        <el-col :span="8" style="height: 400px;background-color: #6a5d5d">
          8
        </el-col>
        <el-col :span="16" style="height: 400px;">
          <h2 style="margin-left: 120px" v-if="loginNum===0">新用户注册</h2>
          <h2 style="margin-left: 120px" v-else>用户登录</h2>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="form-login">

            <el-form-item label="手机号/邮箱" prop="username">
              <el-input v-model="ruleForm.username" class="form-input"/>
              <el-button @click="getYanZhengMa('ruleForm')" style="margin-left: 5px" v-if="loginNum===0">
                发送验证码
              </el-button>
            </el-form-item>

            <el-form-item label="验证码" prop="subPassword" v-if="loginNum===0">
              <el-input v-model="ruleForm.subPassword" class="form-input" :disabled="!isVerificationSent"/>
            </el-form-item>

            <el-form-item :label="loginNum===1? '输入密码' :'设置密码'" prop="password">
              <el-input v-model="ruleForm.password" class="form-input"/>
            </el-form-item>


            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')">
                {{ this.loginNum === 1 ? "点击登录" : "点击注册" }}
              </el-button>
              <el-button @click="loginNum = loginNum === 0 ? 1 : 0">
                {{ this.loginNum === 0 ? "已有帐号，返回登录" : "没有账号，创建新账号" }}
              </el-button>
            </el-form-item>
          </el-form>

        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped>
.app {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background-color: rgba(1, 1, 1, 0.1)
}

.form-login {
  margin: 10px 0 0 20px;
}

.form-input {
  width: 250px;
}
</style>